/**
 * Created by jun on 2018/3/24.
 */
var logManager=require("../Logs.js");
var SystemEvent=require("../event/SystemEvent")
var SocketServerClient=Class.extend({
    id:0,
    port:0,
    connection:null,
    eventManager:null,
    sendMsg:function(msg){
        logManager.logP("send protocol:"+msg)
        this.connection.send(msg);
    },
    ctor:function(id,conn,port,eventManager){
        this.id=id;
        this.port=port;
        this.connection=conn;
        this.eventManager=eventManager;
        // this.connection.beginBinary()
        conn.on("binary",this.onText.bind(this));
        conn.on("text",this.onText.bind(this));
        conn.on("close",this.onClose.bind(this));
        conn.on("error",this.onError.bind(this));
    },
    closeSocket:function(){
        try{
            this.connection.close();
        }catch(e){
            logManager.logM(e);
        }
        this.eventManager.dispatchEvent(SystemEvent.SOCKET_CLOSE,[{clientId:this.id,port:this.port}]);
    },
    onError:function (code, reason) {
        logManager.logM("连接错误：id="+this.id);
        this.eventManager.dispatchEvent(SystemEvent.SOCKET_CLOSE,[{clientId:this.id,port:this.port}]);
    },
    onClose:function (code, reason) {
        logManager.logM("连接关闭：id="+this.id);
        this.eventManager.dispatchEvent(SystemEvent.SOCKET_CLOSE,[{clientId:this.id,port:this.port}]);
    },
    onText:function(str){
        logManager.logP("recive protocal:"+str)
        var data={};
        try{
            data=JSON.parse(str);
        }catch(e){
            // logManager.logE(e.toString());
            // return;
        }
        data.trunk=str;
        data.clientId=this.id;
        data.port=this.port;
        if(data){
            try{this.eventManager.dispatchEvent(SystemEvent.SOCKET_DATA,[data,this.connection]);}catch(e){
                logManager.logE(e.stack)
            }
        }else
            logManager.logE("socket data error:"+str);
    }
})
module.exports=SocketServerClient;